package utils

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

func CreateDir(path string) error {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		err = os.MkdirAll(path, 0777)
		if err != nil {
			return err
		}
	}
	return nil
}

func UploadFile(r *http.Request, field string, savePath string) (map[string]string, error) {
	file, fileHeader, err := r.FormFile(field)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	oldName := fileHeader.Filename
	fileName := GetFileName() + filepath.Ext(oldName)

	savePath = savePath + "/" + fileName
	out, err := os.Create(savePath)
	if err != nil {
		return nil, err
	}
	defer out.Close()
	_, err = io.Copy(out, file)
	if err != nil {
		return nil, err
	}
	fmt.Printf("file %s uploaded ok\n", fileName)
	result := make(map[string]string)
	result["oldName"] = oldName
	result["fileName"] = fileName
	return result, nil
}
